import time

from selenium import webdriver
import selenium.common.exceptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import InvalidArgumentException,WebDriverException,NoSuchElementException

class Base:
    '''
    基础类：分装了selenium基础方法，供page包下面的类继承
    '''

    def __init__(self,browser):
        # TODO 打开浏览器，设置driver
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'Edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    def get(self,url):
        # TODO 请求目标网址
        # selenium.common.exceptions.InvalidArgumentException:Message:invalid argument
        # selenium.common.exceptions.WebDriverException:Message:unknown
        try:
            self.driver.get(url)
        except(InvalidArgumentException,WebDriverException):
            print('输入的地址不正确')

    def find_element(self,locator): # locator = By.xxx,value
        # TODO 定位元素
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def click(self,locator):
        # TODO 元素点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素定位失败')

    def get_attribute(self,locator,param):
        # TODO 获取元素属性 --作业
        # 定位元素，判断属性
        element = self.find_element(locator)
        if element is not None:
            attr = element.get_attribute(param)
            if attr is not None:
                print(attr)
            else:
                print('属性不存在')
        else:
            print('元素定位失败')


    def forword(self):
        # TODO 前进
        self.driver.back()

    def back(self):
        # TODO 后退
        self.driver.back()

    def refresh(self):
        # TODO 刷新浏览器
        self.driver.refresh()

    def quit(self,seconds=0):
        # TODO 关闭浏览器
        time.sleep(seconds)
        self.driver.quit()

if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element((By.ID,'kw'))
    base.click((By.LINK_TEXT,'图片'))
    base.get_attribute((By.ID,'su'))
    base.forword()
    base.back()
    base.refresh()